import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
import _applyDecoratedDescriptor from "@babel/runtime/helpers/esm/applyDecoratedDescriptor";
import _map from "lodash/map";
import _isEmpty from "lodash/isEmpty";
import _forEach from "lodash/forEach";
import _find from "lodash/find";
import _differenceWith from "lodash/differenceWith";
var _excluded = ["form", "userRecord", "isCreate", "fetchGroups"];

var _dec, _dec2, _dec3, _dec4, _dec5, _dec6, _dec7, _dec8, _dec9, _dec10, _dec11, _dec12, _dec13, _class, _class2;

/**
 * EditModal.js
 * 当编辑自己的账号时, 用户组时不可以新增和删除的
 * @date 2018-1-15

 */
import React from 'react';
import { Checkbox, Col, Form, Input, Modal, Row } from 'antd';
import { Bind } from 'lodash-decorators';
import EditTable from 'components/EditTable';
import { Button as ButtonPermission } from 'components/Permission';
import intl from 'utils/intl';
import { addItemsToPagination, createPagination, delItemsToPagination, getEditTableData, tableScrollWidth } from 'utils/utils';
import notification from 'utils/notification';
import styles from "../../index.less?modules";
import GroupModal from "./GroupModal";
var formItemLayout = {
  labelCol: {
    span: 3
  },
  wrapperCol: {
    span: 20
  }
};
var UserGroupModal = (_dec = Form.create({
  fieldNameProp: null
}), _dec2 = Bind(), _dec3 = Bind(), _dec4 = Bind(), _dec5 = Bind(), _dec6 = Bind(), _dec7 = Bind(), _dec8 = Bind(), _dec9 = Bind(), _dec10 = Bind(), _dec11 = Bind(), _dec12 = Bind(), _dec13 = Bind(), _dec(_class = (_class2 = /*#__PURE__*/function (_React$Component) {
  _inherits(UserGroupModal, _React$Component);

  var _super = _createSuper(UserGroupModal);

  function UserGroupModal() {
    var _this;

    _classCallCheck(this, UserGroupModal);

    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    _this = _super.call.apply(_super, [this].concat(args));
    _this.state = {
      selectedRowKeys: [],
      groupModalProps: {},
      // 新建用户组框
      // 用户组表格的信息
      dataSource: [],
      pagination: false,
      groupTableFetchLoading: false // 用户组加载数据 和 翻页改变

    };
    _this.groupPaginationCache = void 0;
    return _this;
  }

  _createClass(UserGroupModal, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      var _this$props$isCreate = this.props.isCreate,
          isCreate = _this$props$isCreate === void 0 ? true : _this$props$isCreate;

      if (!isCreate) {
        this.handleGroupTableChange();
      }
    }
  }, {
    key: "changeCountryId",
    value: function changeCountryId() {
      var setFieldsValue = this.props.form.setFieldsValue;
      setFieldsValue({
        regionId: undefined
      });
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props = this.props,
          form = _this$props.form,
          _this$props$userRecor = _this$props.userRecord,
          userRecord = _this$props$userRecor === void 0 ? {} : _this$props$userRecor,
          isCreate = _this$props.isCreate,
          fetchGroups = _this$props.fetchGroups,
          modalProps = _objectWithoutProperties(_this$props, _excluded); // todo 租户id 明天问下 明伟哥。


      var _this$state$groupModa = this.state.groupModalProps,
          groupModalProps = _this$state$groupModa === void 0 ? {} : _this$state$groupModa;
      return /*#__PURE__*/React.createElement(Modal, Object.assign({
        title: intl.get('ciam.subAccount.view.message.title.userGroup').d('用户组分配'),
        wrapClassName: "ant-modal-sidebar-right",
        transitionName: "move-right",
        width: 600,
        closable: false
      }, modalProps, {
        onOk: this.handleEditModalOk
      }), this.renderForm(), groupModalProps.visible && /*#__PURE__*/React.createElement(GroupModal, Object.assign({}, groupModalProps, {
        fetchGroups: fetchGroups,
        onSave: this.handleGroupCreateSave,
        onCancel: this.handleGroupCreateCancel,
        tenantId: userRecord.organizationId
      })));
    }
  }, {
    key: "renderForm",
    value: function renderForm() {
      var _this$props2 = this.props,
          path = _this$props2.path,
          form = _this$props2.form,
          _this$props2$userReco = _this$props2.userRecord,
          userRecord = _this$props2$userReco === void 0 ? {} : _this$props2$userReco;
      var _this$state = this.state,
          _this$state$selectedR = _this$state.selectedRowKeys,
          selectedRowKeys = _this$state$selectedR === void 0 ? [] : _this$state$selectedR,
          _this$state$dataSourc = _this$state.dataSource,
          dataSource = _this$state$dataSourc === void 0 ? [] : _this$state$dataSourc,
          _this$state$paginatio = _this$state.pagination,
          pagination = _this$state$paginatio === void 0 ? false : _this$state$paginatio,
          groupTableFetchLoading = _this$state.groupTableFetchLoading;
      var rowSelection = {
        selectedRowKeys: selectedRowKeys,
        onChange: this.handleRowSelectChange
      };
      var tableColumns = this.getGroupColumns();
      var groupNode = /*#__PURE__*/React.createElement(React.Fragment, {
        key: "group-no-same-user-btn"
      }, /*#__PURE__*/React.createElement(Row, {
        style: {
          textAlign: 'right',
          marginBottom: 16
        }
      }, /*#__PURE__*/React.createElement(Col, {
        span: 23
      }, /*#__PURE__*/React.createElement(ButtonPermission, {
        permissionList: [{
          code: "".concat(path, ".button.deleteUserGroup"),
          type: 'button',
          meaning: '子账户管理-删除用户组'
        }],
        style: {
          marginRight: 8
        },
        onClick: this.handleGroupRemove,
        disabled: selectedRowKeys.length === 0
      }, intl.get('cpaas.common.button.delete').d('删除')), /*#__PURE__*/React.createElement(ButtonPermission, {
        permissionList: [{
          code: "".concat(path, ".button.createUserGroup"),
          type: 'button',
          meaning: '子账户管理-新建用户组'
        }],
        type: "primary",
        onClick: this.handleGroupCreate
      }, intl.get('cpaas.common.button.create').d('新建'))), /*#__PURE__*/React.createElement(Col, {
        span: 1
      })), /*#__PURE__*/React.createElement(Row, {
        type: "flex"
      }, /*#__PURE__*/React.createElement(Col, {
        span: 3
      }), /*#__PURE__*/React.createElement(Col, {
        span: 20,
        className: styles['rule-table']
      }, /*#__PURE__*/React.createElement(EditTable, {
        bordered: true,
        rowKey: "userGroupId",
        dataSource: dataSource,
        pagination: pagination,
        loading: groupTableFetchLoading,
        columns: tableColumns,
        scroll: {
          x: tableScrollWidth(tableColumns)
        },
        onChange: this.handleGroupTableChange,
        rowSelection: rowSelection
      }))));
      return /*#__PURE__*/React.createElement(Form, null, /*#__PURE__*/React.createElement(Form.Item, Object.assign({}, formItemLayout, {
        label: intl.get('ciam.subAccount.model.user.loginName').d('账号')
      }), form.getFieldDecorator('loginName', {
        initialValue: userRecord.loginName
      })( /*#__PURE__*/React.createElement(Input, {
        disabled: true
      }))), /*#__PURE__*/React.createElement(Form.Item, Object.assign({}, formItemLayout, {
        label: intl.get('ciam.subAccount.model.user.realName').d('名称')
      }), form.getFieldDecorator('realName', {
        initialValue: userRecord.realName
      })( /*#__PURE__*/React.createElement(Input, {
        disabled: true
      }))), /*#__PURE__*/React.createElement(Form.Item, Object.assign({}, formItemLayout, {
        label: intl.get('ciam.subAccount.model.user.tenant').d('所属租户')
      }), form.getFieldDecorator('tenantName', {
        initialValue: userRecord.tenantName
      })( /*#__PURE__*/React.createElement(Input, {
        disabled: true
      }))), /*#__PURE__*/React.createElement(Row, null, groupNode));
    }
    /**
     * 用户组 table 分页改变
     * 如果是新增用户 分页是
     * @param {object} page
     * @param {object} filter
     * @param {object} sort
     */

  }, {
    key: "handleGroupTableChange",
    value: function handleGroupTableChange(page, filter, sort) {
      var _this2 = this;

      var _this$props3 = this.props,
          fetchCurrentUserGroups = _this$props3.fetchCurrentUserGroups,
          _this$props3$isCreate = _this$props3.isCreate,
          isCreate = _this$props3$isCreate === void 0 ? true : _this$props3$isCreate,
          _this$props3$userReco = _this$props3.userRecord,
          userRecord = _this$props3$userReco === void 0 ? {} : _this$props3$userReco;

      if (!isCreate) {
        this.showGroupTableLoading();
        fetchCurrentUserGroups({
          page: page,
          sort: sort,
          userId: userRecord.id
        }).then(function (groupContent) {
          // 在前面中已经 getResponse 了
          if (groupContent) {
            _this2.setState({
              dataSource: _map(groupContent.content, function (r) {
                return _objectSpread(_objectSpread({}, r), {}, {
                  _status: 'update'
                });
              }),
              pagination: createPagination(groupContent)
            }, function () {
              for (var i = 0; i < groupContent.content.length; i++) {
                if (groupContent.content[i].defaultFlag === 1) {
                  _this2.setState({
                    defaultGroupId: groupContent.content[i].userGroupId
                  });
                }
              }
            });
          }
        }).finally(function () {
          _this2.hiddenGroupTableLoading();
        });
      }
    }
  }, {
    key: "showGroupTableLoading",
    value: function showGroupTableLoading() {
      this.setState({
        groupTableFetchLoading: true
      });
    }
  }, {
    key: "hiddenGroupTableLoading",
    value: function hiddenGroupTableLoading() {
      this.setState({
        groupTableFetchLoading: false
      });
    }
  }, {
    key: "getGroupColumns",
    value: function getGroupColumns() {
      var _this3 = this;

      if (!this.groupColumns) {
        this.groupColumns = [{
          title: intl.get('ciam.subAccount.model.group.groupCode').d('用户组编码'),
          dataIndex: 'groupCode',
          width: 200
        }, {
          title: intl.get('ciam.subAccount.model.group.groupName').d('用户组名称'),
          dataIndex: 'groupName',
          width: 120
        }, {
          title: intl.get('ciam.subAccount.model.group.defaultGroupId').d('默认'),
          key: 'defaultFlag',
          width: 80,
          render: function render(_, record) {
            var defaultGroupId = _this3.state.defaultGroupId;
            return /*#__PURE__*/React.createElement(Checkbox, {
              checked: record.userGroupId === defaultGroupId,
              onClick: function onClick() {
                _this3.handleGroupDefaultChange(record.userGroupId);
              }
            });
          }
        }];
      }

      return this.groupColumns;
    }
  }, {
    key: "handleRowSelectChange",
    value: function handleRowSelectChange(_) {
      var selectedRows = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
      this.setState({
        selectedRowKeys: _map(selectedRows, function (r) {
          return r.userGroupId;
        }),
        selectedRows: selectedRows
      });
    }
  }, {
    key: "handleGroupDefaultChange",
    value: function handleGroupDefaultChange(groupId) {
      var defaultGroupId = this.state.defaultGroupId;

      if (defaultGroupId === groupId) {
        this.setState({
          defaultGroupId: undefined
        });
      } else {
        this.setState({
          defaultGroupId: groupId
        });
      }
    }
  }, {
    key: "handleGroupRemove",
    value: function handleGroupRemove() {
      var _this4 = this;

      Modal.confirm({
        title: intl.get('cpaas.common.message.confirm.title').d('提示'),
        content: intl.get("ciam.subAccount.view.message.title.content").d('确定删除吗？'),
        onOk: function onOk() {
          var _this4$state = _this4.state,
              _this4$state$selected = _this4$state.selectedRows,
              selectedRows = _this4$state$selected === void 0 ? [] : _this4$state$selected,
              _this4$state$defaultG = _this4$state.defaultGroupId,
              defaultGroupId = _this4$state$defaultG === void 0 ? -1 : _this4$state$defaultG;
          var _this4$props = _this4.props,
              _this4$props$userReco = _this4$props.userRecord,
              userRecord = _this4$props$userReco === void 0 ? {} : _this4$props$userReco,
              onGroupRemove = _this4$props.onGroupRemove;
          var remoteRemoveDataSource = [];
          var updateDefaultGroupId = defaultGroupId;

          _forEach(selectedRows, function (r) {
            if (r.userGroupId === defaultGroupId) {
              updateDefaultGroupId = -1;
            }

            if (r._status === 'update') {
              remoteRemoveDataSource.push(_objectSpread({}, r));
            }
          });

          if (remoteRemoveDataSource.length > 0) {
            onGroupRemove({
              userId: userRecord.id,
              remoteRemoveDataSource: remoteRemoveDataSource
            }).then(function (res) {
              if (res) {
                _this4.removeLocaleGroups(updateDefaultGroupId);

                notification.success();
              }
            });
          } else {
            _this4.removeLocaleGroups(updateDefaultGroupId);
          }
        }
      });
    }
  }, {
    key: "removeLocaleGroups",
    value: function removeLocaleGroups(updateDefaultGroupId) {
      var nextState = {};

      if (updateDefaultGroupId === -1) {
        nextState.defaultGroupId = -1;
      }

      var _this$state2 = this.state,
          _this$state2$dataSour = _this$state2.dataSource,
          dataSource = _this$state2$dataSour === void 0 ? [] : _this$state2$dataSour,
          _this$state2$selected = _this$state2.selectedRowKeys,
          selectedRowKeys = _this$state2$selected === void 0 ? [] : _this$state2$selected,
          _this$state2$paginati = _this$state2.pagination,
          pagination = _this$state2$paginati === void 0 ? {} : _this$state2$paginati;
      var _this$props$isCreate2 = this.props.isCreate,
          isCreate = _this$props$isCreate2 === void 0 ? true : _this$props$isCreate2;
      nextState.dataSource = _differenceWith(dataSource, selectedRowKeys, function (r1, r2) {
        return r1.userGroupId === r2;
      });
      nextState.pagination = isCreate ? false : delItemsToPagination(selectedRowKeys.length, dataSource.length, pagination);
      nextState.selectedRowKeys = [];
      nextState.selectedRows = [];
      this.setState(nextState);
    }
  }, {
    key: "handleGroupCreate",
    value: function handleGroupCreate() {
      var _this$props4 = this.props,
          _this$props4$userReco = _this$props4.userRecord,
          userRecord = _this$props4$userReco === void 0 ? {} : _this$props4$userReco,
          _this$props4$isCreate = _this$props4.isCreate,
          isCreate = _this$props4$isCreate === void 0 ? true : _this$props4$isCreate;
      var _this$state$dataSourc2 = this.state.dataSource,
          dataSource = _this$state$dataSourc2 === void 0 ? [] : _this$state$dataSourc2;
      var userId = []; // 当前编辑账号的账号id( 需要的排除账号对应的用户组 )

      var excludeIds = []; // 当前已选择的用户组id

      if (!isCreate) {
        userId.push(userRecord.id);
      }

      dataSource.forEach(function (group) {
        if (group._status === 'create') {
          excludeIds.push(group.userGroupId);
        }
      });
      this.setState({
        groupModalProps: {
          visible: true,
          userId: userId,
          excludeIds: excludeIds
        }
      });
    }
  }, {
    key: "handleGroupCreateSave",
    value: function handleGroupCreateSave(groups) {
      if (groups && groups.length > 0) {
        var _this$state3 = this.state,
            _this$state3$dataSour = _this$state3.dataSource,
            dataSource = _this$state3$dataSour === void 0 ? [] : _this$state3$dataSour,
            _this$state3$paginati = _this$state3.pagination,
            pagination = _this$state3$paginati === void 0 ? {} : _this$state3$paginati;
        var _this$props5 = this.props,
            _this$props5$isCreate = _this$props5.isCreate,
            isCreate = _this$props5$isCreate === void 0 ? true : _this$props5$isCreate,
            _this$props5$userReco = _this$props5.userRecord,
            userRecord = _this$props5$userReco === void 0 ? {} : _this$props5$userReco;
        this.setState({
          dataSource: [].concat(_toConsumableArray(dataSource), _toConsumableArray(groups.map(function (group) {
            return {
              groupCode: group.groupCode,
              groupName: group.groupName,
              userGroupId: group.userGroupId,
              sourceType: group.level,
              defaultFlag: group.defaultFlag,
              tenantName: userRecord.tenantName,
              _status: 'create'
            };
          }))),
          pagination: isCreate ? false : addItemsToPagination(groups.length, dataSource.length, pagination)
        });
      }

      this.handleGroupCreateCancel();
    }
  }, {
    key: "handleGroupCreateCancel",
    value: function handleGroupCreateCancel() {
      this.setState({
        groupModalProps: {
          visible: false
        }
      });
    }
  }, {
    key: "handleEditModalOk",
    value: function handleEditModalOk() {
      var _this$props$userRecor2 = this.props.userRecord,
          userRecord = _this$props$userRecor2 === void 0 ? {} : _this$props$userRecor2;
      var _this$state4 = this.state,
          _this$state4$dataSour = _this$state4.dataSource,
          dataSource = _this$state4$dataSour === void 0 ? [] : _this$state4$dataSour,
          defaultGroupId = _this$state4.defaultGroupId;
      var memberGroupList = [];
      var validateDataSource = getEditTableData(dataSource);
      validateDataSource.forEach(function (r) {
        var newGroup = {
          assignId: r.assignId,
          defaultFlag: r.userGroupId === defaultGroupId ? 1 : 0,
          groupCode: r.groupCode,
          groupName: r.groupName,
          tenantId: userRecord.organizationId,
          tenantName: userRecord.tenantName,
          userGroupId: r.userGroupId,
          userId: userRecord.id,
          _token: r._token,
          objectVersionNumber: r.objectVersionNumber
        };

        var oldR = _find(dataSource, function (or) {
          return or.userGroupId === r.userGroupId;
        });

        if (oldR._status === 'create' || oldR._status === 'update' && oldR.defaultFlag !== newGroup.defaultFlag) {
          memberGroupList.push(newGroup);
        }
      });

      if (dataSource.length !== 0 && dataSource.length !== validateDataSource.length) {
        // 用户组校验 失败
        return;
      }

      var onOk = this.props.onOk;
      var saveData = {
        userId: userRecord.id,
        memberGroupList: memberGroupList
      };
      onOk(saveData);
    }
  }], [{
    key: "getDerivedStateFromProps",
    value: function getDerivedStateFromProps(nextProps, prevState) {
      var _nextProps$isCreate = nextProps.isCreate,
          isCreate = _nextProps$isCreate === void 0 ? true : _nextProps$isCreate,
          _nextProps$userRecord = nextProps.userRecord;
      _nextProps$userRecord = _nextProps$userRecord === void 0 ? {} : _nextProps$userRecord;
      var defaultGroupId = _nextProps$userRecord.defaultGroupId;
      var nextState = {};

      if (isCreate && prevState.pagination !== false) {
        nextState.pagination = false;
      }

      if (defaultGroupId !== prevState.initDefaultGroupId) {
        nextState.defaultGroupId = defaultGroupId;
        nextState.initDefaultGroupId = defaultGroupId;
      }

      if (_isEmpty(nextState)) {
        return null;
      }

      return nextState;
    }
  }]);

  return UserGroupModal;
}(React.Component), (_applyDecoratedDescriptor(_class2.prototype, "changeCountryId", [_dec2], Object.getOwnPropertyDescriptor(_class2.prototype, "changeCountryId"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleGroupTableChange", [_dec3], Object.getOwnPropertyDescriptor(_class2.prototype, "handleGroupTableChange"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "showGroupTableLoading", [_dec4], Object.getOwnPropertyDescriptor(_class2.prototype, "showGroupTableLoading"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "hiddenGroupTableLoading", [_dec5], Object.getOwnPropertyDescriptor(_class2.prototype, "hiddenGroupTableLoading"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleRowSelectChange", [_dec6], Object.getOwnPropertyDescriptor(_class2.prototype, "handleRowSelectChange"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleGroupDefaultChange", [_dec7], Object.getOwnPropertyDescriptor(_class2.prototype, "handleGroupDefaultChange"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleGroupRemove", [_dec8], Object.getOwnPropertyDescriptor(_class2.prototype, "handleGroupRemove"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "removeLocaleGroups", [_dec9], Object.getOwnPropertyDescriptor(_class2.prototype, "removeLocaleGroups"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleGroupCreate", [_dec10], Object.getOwnPropertyDescriptor(_class2.prototype, "handleGroupCreate"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleGroupCreateSave", [_dec11], Object.getOwnPropertyDescriptor(_class2.prototype, "handleGroupCreateSave"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleGroupCreateCancel", [_dec12], Object.getOwnPropertyDescriptor(_class2.prototype, "handleGroupCreateCancel"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleEditModalOk", [_dec13], Object.getOwnPropertyDescriptor(_class2.prototype, "handleEditModalOk"), _class2.prototype)), _class2)) || _class);
export { UserGroupModal as default };